using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SpoonFilesystem
{
	public class FileCache
	{
		private static string _fileName = "F:/filecache.dat";
		private static int _size = 100;

		private List<FileHeader> _headerList = new List<FileHeader>();

		private FileStream _file = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

		public FileCache()
		{
			LoadHeader();
		}

		public FileHeader Write(byte[] data)
		{
			FileHeader header = new FileHeader((ulong)new Random().Next());
			header.Data = data;
			Add(header);
			return header;
		}

		private void Add(FileHeader header)
		{
			if(_headerList.Count < _size) _headerList.Add(header);
			else
			{
				_headerList.Sort();
				_headerList.RemoveAt(0);
				_headerList.Add(header);
			}
		}

		public void Flush()
		{
			_file.SetLength(0);
			BinaryWriter bw = new BinaryWriter(_file);
			foreach (FileHeader header in _headerList)
			{
				header.Write(bw);
			}
			_file.Flush();
		}

		private void LoadHeader()
		{
			int size = FileHeader.HeaderSize + FileHeader.BlockSize;
			int pos = 0;
			BinaryReader br = new BinaryReader(_file);
			while (size * pos < _file.Length)
			{
				_file.Position = size * pos;
				FileHeader header = new FileHeader(br);
				_headerList.Add(header);
				pos++;
			}
		}
	}
}
